#include"DList.h"

DLNode* DLInit()
{
	DLNode* newhead = (DLNode*)malloc(sizeof(DLNode));
	if (newhead == NULL)
	{
		perror("DLInit->malloc failed");
		exit(-1);
	}
	newhead->next = newhead;
	newhead->prev = newhead;
	return newhead;
}

void DLDestroy(DLNode* phead)
{
	assert(phead);
	DLNode* cur = phead->next;
	while (cur != phead)
	{
		DLNode* del = cur;
		cur = cur->next;
		free(del);
	}
	free(cur);

}

DLNode* BuyDLNode(DLDataType x)
{
	DLNode* newnode = (DLNode*)malloc(sizeof(DLNode));
	if (newnode == NULL)
	{
		perror("BuuDLNode->malloc failed");
		exit(-1);
	}
	newnode->a = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void DLPushBack(DLNode* phead, DLDataType x)
{
	assert(phead);
	DLNode* newnode = BuyDLNode(x);
	DLNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void DLPrint(DLNode* phead)
{
	assert(phead);
	DLNode* cur = phead->next;
	printf("head<=>");
	while (cur != phead)
	{
		printf("%d<=>", cur->a);
		cur = cur->next;
	}
	printf("\n");
}


void DLPushFront(DLNode* phead, DLDataType x)
{
	assert(phead);
	DLNode* newnode = BuyDLNode(x);
	DLNode* oldhead = phead->next;
	newnode->next = oldhead;
	oldhead->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}
void DLPopBack(DLNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	DLNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
}
void DLInsert(DLNode* phead, DLNode* pos, DLDataType x)
{
	assert(phead);
	assert(pos);
	assert(phead != pos);
	DLNode* newnode = BuyDLNode(x);
	DLNode* posPrev = pos->prev;
	posPrev->next = newnode;
	newnode->prev = posPrev;
	newnode->next = pos;
	pos->prev = newnode;
}

void DLInsertAfter(DLNode* pos, DLDataType x)
{
	assert(pos);
	DLNode* newnode = BuyDLNode(x);
	DLNode* posNext = pos->next;
	pos->next = newnode;
	newnode->prev = pos;
	newnode->next = posNext;
	posNext->prev = newnode;
}
void DLErase(DLNode* pos)
{
	assert(pos);
	DLNode* posPrev = pos->prev;
	DLNode* posNext = pos->next;
	posPrev->next = posNext;
	posNext->prev = posPrev;
}
DLNode* DLFind(DLNode* phead, DLDataType x)
{
	assert(phead);
	DLNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->a == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}



